package server_common

import (
	"context"
	"grpc_demo/conf"
	"grpc_demo/internal/dao"
	"grpc_demo/pkg/logger"
	"grpc_demo/pkg/redis"
	"os"
	"os/signal"
	"syscall"
	"time"
)

// Init 初始化应用
func Init(ctx context.Context) (func(), error) {

	conf.InitConf()
	// 初始化日志
	loggerCleanFunc := logger.InitLogger()
	if err := redis.InitRedis(); err != nil {
		logger.WithContext(ctx).Errorf("Redis Init error %v", err)
		return nil, err
	}

	if err := dao.InitGorm(); err != nil {
		logger.WithContext(ctx).Errorf("Db Init error %v", err)
		return nil, err
	}

	// 初始化RPC服务
	httpServerCleanFunc := InitRpcServer(ctx)
	logger.WithContext(ctx).Infof("服务启动，运行模式：%s，进程号：%d", conf.ConfigInstance.Mode, os.Getpid())

	return func() {
		httpServerCleanFunc()
		loggerCleanFunc()
	}, nil
}

// Run 运行服务
func Run(ctx context.Context) error {
	state := 1
	sc := make(chan os.Signal, 1)
	signal.Notify(sc, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
	cleanFunc, err := Init(ctx)
	if err != nil {
		return err
	}
EXIT:
	for {
		sig := <-sc
		logger.WithContext(ctx).Infof("接收到信号[%v]", sig.String())
		switch sig {
		case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
			state = 0
			break EXIT
		case syscall.SIGHUP:
		default:
			break EXIT
		}
	}

	logger.WithContext(ctx).Infof("服务将在1s后退出")
	cleanFunc()
	time.Sleep(time.Second)
	os.Exit(state)
	return nil
}
